import Util from '@/common/util'
import accountApi from '@/api/accountApi'
import routes from '@/router/routes'
import {cookiePrefix} from '@/common/config'

const store = {
  namespaced: true,
  state: {
    token: Util.getCookie(cookiePrefix + 'token'),
    menus: '',
    components: '',
    // 当前考试类型id
    typeId: '',
    // 当前考试科目id
    subjectId: '',
    testMaps: {},
    username: ''
  },
  mutations: {
    setToken (state, token) {
      Util.setCookie(cookiePrefix + 'token', token)
      state.token = token
    },
    setMenus (state, menus) {
      state.menus = menus
    },
    setUsername (state, username) {
      state.username = username
    },
    setComponents (state, components) {
      state.components = components
    },
    logout (state) {
      Util.delCookie(cookiePrefix + 'token')
      state.token = ''
      state.menus = ''
      state.components = ''
    }
  },
  actions: {
    getAuths ({commit, dispatch}) {
      return accountApi.authInfo().then(data => {
        commit('setUsername', data.username)
        if (Array.isArray(data.menus)) {
          dispatch('setTypesMap', data.menus)
        } else {
          commit('logout')
          throw new Error('无权限信息, 请尝试重新登录')
        }
      })
    },
    setTypesMap ({commit}, arr) {
      if (!Array.isArray(arr) || !arr.length) {
        commit('setMenus', [])
        commit('setComponents', [])
      } else {
        const {menus, components} = handleAuthTree(arr[0])
        commit('setMenus', menus)
        commit('setComponents', components)
      }
    }
  },
  getters: {
    menuList: (state, getters) => Util.getMenuList(routes, getters.menuMap),
    menuMap: state => Array.isArray(state.menus) ?
        state.menus.reduce((map, item) => ((map[item] = true) && map), {}) : {},
    componentMap: state => Array.isArray(state.components) ?
        state.components.reduce((map, item) => ((map[item] = true) && map), {}) : {}
  }
}

// 从树中取权限标识
function handleAuthTree (tree) {
  const menus = []
  const components = []

  handleArrayData(tree.children)
  console.log(menus);
  console.log(components)
  return {
    menus,
    components
  }

  function handleArrayData (arr) {
    if (!arr) return
    arr.forEach(item => {
      if (!!item.frontToolName) {
        if (item.menuType === 0) {
          menus.push(item.frontToolName)
        } else if (item.menuType === 1) {
          components.push(item.frontToolName)
        }
      }
      if (item.children.length > 0) {
        handleArrayData(item.children)
      }
    })
  }
}

export default store
